<?php
App::uses('AppController', 'Controller');
/**
 * Orders Controller
 *
 * @property Order $Order
 * @property PaginatorComponent $Paginator
 */
class OrdersController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');
        public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow('complete_order', 'cancel_order');
        }
/**
 * index method
 *
 * @return void
 */
	public function index() {
                #debug($this->Session->read('Auth.User'));
		$this->Order->recursive = 0;
		$this->set('orders', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->Order->exists($id)) {
			throw new NotFoundException(__('Invalid order'));
		}
		$options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
		$this->set('order', $this->Order->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Order->create();
                        $this->request->data['Order']['operador'] = $this->Auth->user('id');
                        $this->request->data['Order']['emision'] = date('Y-m-d H:i', time());
                        $fecha = explode("/", $this->request->data['Order']['fecha']);
                        $this->request->data['Order']['envio']['day'] = $fecha[0];
                        $this->request->data['Order']['envio']['month'] = $fecha[1];
                        $this->request->data['Order']['envio']['year'] = $fecha[2];
                        $this->guardarPedido($this->request->data);
		}
		$clients = $this->Order->Client->find('list');
                $usuario = $this->Auth->user('type');
                $userid = $this->Auth->user('id');
                if ($usuario === 'Superusuario' || $usuario === 'Administrador'){
                    $companies = $this->Order->Company->find('list');
                }
                else{
                    $this->loadModel('Company'); 
                    $companies = $this->Company->getCompaniesByUserId($userid);
                }
                $distribuidors = $this->Order->distribuidor->find('list', array('conditions' => array('distribuidor.type' => 'Distribuidor')));
		$this->set(compact('clients', 'companies', 'operadors', 'distribuidors'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->Order->exists($id)) {
			throw new NotFoundException(__('Invalid order'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->Order->save($this->request->data)) {
				$this->Session->setFlash(__('The order has been saved.'));
				return $this->redirect(array('action' => 'view', $id));
			} else {
				$this->Session->setFlash(__('The order could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
			$this->request->data = $this->Order->find('first', $options);
		}
		$clients = $this->Order->Client->find('list');
                $op = $this->Order->findById($id, array('fields' => 'operador'));
                $operadors = $this->Order->operador->find('list', array('conditions' => array('operador.id' => $op['Order']['operador'])));
                $usuario = $this->Auth->user('type');
                $userid = $this->Auth->user('id');
                if ($usuario === 'Superusuario' || $usuario === 'Administrador'){
                    $companies = $this->Order->Company->find('list');
                }
                else{
                    $this->loadModel('Company'); 
                    $companies = $this->Company->getCompaniesByUserId($userid);
                }
                $distribuidors = $this->Order->distribuidor->find('list', array('conditions' => array('distribuidor.type' => 'Distribuidor')));
		$this->set(compact('distribuidors', 'clients', 'companies', 'operadors'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Order->id = $id;
		if (!$this->Order->exists()) {
			throw new NotFoundException(__('Invalid order'));
		}
		$this->request->allowMethod('post', 'delete');
		if ($this->Order->delete()) {
			$this->Session->setFlash(__('The order has been deleted.'));
		} else {
			$this->Session->setFlash(__('The order could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
        
        public function isAuthorized($user) {
            // All registered users can add posts
            if (in_array($this->action, array('add', 'edit', 'delete'))) {
                //$usuario = $this->request->params['pass'][0];
                //if ($this->Auth->user('id') === $usuario){
                    return true;
                //}
            }

            // The owner of a post can edit and delete it
            //if (in_array($this->action, array('edit', 'delete'))) {
            //    $postId = (int) $this->request->params['pass'][0];
            //    if ($this->Post->isOwnedBy($postId, $user['id'])) {
            //        return true;
            //    }
            //}

            return parent::isAuthorized($user);
        }
        
        public function direccion($rif = null){
		
		
		$this->layout = false;
		if ($this->request->is('get')) 
		{
		$direccion = $this->Order->Client->find('all', array('conditions' => array('Client.rif' => $rif)));
                if ($direccion != null){
		$this->set('direccion', $direccion[0]);
                }
		
		}
                
                $this->render('/Elements/direccion');
	
	}
        
        private function guardarPedido($data){
            if (isset($data['Client']['id'])){
                $data['Order']['client_id'] = $data['Client']['id'];
                if ($this->Order->save($data)) {
                    if (isset($data['Order']['comentario'])){
                        $data['Comment']['user_id'] = $this->Auth->user('id');
                        $data['Comment']['order_id'] = $this->Order->id;
                        $data['Comment']['comentario'] = $this->request->data['Order']['comentario'];
                        $data['Comment']['created'] = date('Y-m-d H:i', time());
                        $this->Order->Comment->save($data);
                    }
                    $this->Session->setFlash(__('The order has been saved.'));
                    return $this->redirect(array('action' => 'index'));
                } 
                else {
                    $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                }
            }
            else{
                if ($this->Order->Client->save($data)){
                    $data['Order']['client_id'] = $this->Order->Client->id;
                    if ($this->Order->save($data)) {
                        $this->Session->setFlash(__('The order has been saved.'));
                        if (isset($data['Order']['comentario'])){
                            $data['Comment']['user_id'] = $this->Auth->user('id');
                            $data['Comment']['order_id'] = $this->Order->id;
                            $data['Comment']['comentario'] = $this->request->data['Order']['comentario'];
                            $data['Comment']['created'] = date('Y-m-d H:i', time());
                            $this->Order->Comment->save($data);
                        }
                        return $this->redirect(array('action' => 'index'));
                    } 
                    else {
                        $this->Order->Client->delete($this->Order->Client->id);
                        $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                    }
                }
                else {
                    $this->Session->setFlash(__('The client could not be saved. Please, try again.'));
                }
            }
            
        }
/**
 * cancelar method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function cancelar($id = null) {
		$this->Order->id = $id;
		if (!$this->Order->exists()) {
			throw new NotFoundException(__('Invalid order'));
		}
		$this->request->allowMethod('post', 'delete');
                $this->Order->set('status', 'Cancelada');
		if ($this->Order->save()) {
			$this->Session->setFlash(__('El pedido fue cancelado.'));
		} else {
			$this->Session->setFlash(__('El pedido no pudo ser cancelado. Intente de nuevo.'));
		}
		return $this->redirect(array('action' => 'view', $id));
	}
        
/**
 * search method
 *
 * @return void
 */
	public function search($fecha = 'mes') {
		$this->Order->recursive = 0;
                $date = date('Y-m-d', time());
                if ($fecha == 'dia'){
                    $paginate = array(
			'conditions' => array('(DATEDIFF(Order.emision,"'.$date.'") = 0)')
                    );
                    
                }
                
                // ESTO ES SI SE QUIERE QUE SE MUESTRE SOLO LOS DE ESTA SEMANA DEL AÑO
                if ($fecha == 'semana'){    
                    $paginate = array(
			'conditions' => array('("' . $date . '" - INTERVAL 1 WEEK < Order.emision)')
                    );
                }
                
                // ESTO ES SI SE QUIERE QUE SEA DESDE HACE UNA SEMANA HASTA HOY
                //if ($fecha == 'semana'){    
                //    $paginate = array(
		//	'conditions' => array('(WEEKOFYEAR("' . $date . '") = WEEKOFYEAR(Order.emision))')
                //    );
                //}
                
                // MUESTRA LOS PEDIDOS DEL MES ACTUAL
                if ($fecha == 'mes'){
                    $paginate = array(
			'conditions' => array('(MONTH("' . $date . '") = MONTH(Order.emision))')
                    );
                }
		
                $this->Paginator->settings = $paginate;
		$this->set('orders', $this->Paginator->paginate());
	}
    
/**
 * my_orders method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function my_orders($id = null) {
		
                $options = array('conditions' => array('Order.distribuidor'  => $id));
                $orders = $this->Order->find('all', $options);
                $this->response->type('json');
		$this->response->body(json_encode($orders));
		return $this->response;
	}  
        
/**
 * complete_order method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function complete_order($id = null) {
		
                $user = $this->Session->read('Auth.User');
                if ($user == null){
                    $arrReturn['status'] = 'NOTLOGGEDIN';
                    $arrReturn['data'] = array( 'loginSuccess' => 0 );
                }
                else {
                    $options = array('conditions' => array('Order.id'  => $id));
                    $order = $this->Order->find('first', $options);
                    if ($order != null){
                        $this->Order->id = $id;
                        $this->Order->set('status', 'Entregada');
                        if ($this->Order->save()){
                            $arrReturn['status'] = 'SUCCESS';
                            $arrReturn['data'] = $order;
                        }
                        else {
                            $arrReturn['status'] = 'FAILED';
                        }
                        
                    }
                    else{
                        $arrReturn['status'] = 'ORDERNOTFOUND';
                    }
                }
                
                $this->response->type('json');
		$this->response->body(json_encode($arrReturn));
		return $this->response;
	} 
        
/**
 * cancel_order method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function cancel_order($id = null) {
		
                $user = $this->Session->read('Auth.User');
                if ($user == null){
                    $arrReturn['status'] = 'NOTLOGGEDIN';
                }
                else {
                    $options = array('conditions' => array('Order.id'  => $id));
                    $order = $this->Order->find('first', $options);
                    if ($order != null){
                        $this->Order->id = $id;
                        $this->Order->set('status', 'Cancelada');
                        if ($this->Order->save()){
                            $arrReturn['status'] = 'SUCCESS';
                            $arrReturn['data'] = $order;
                        }
                        else {
                            $arrReturn['status'] = 'FAILED';
                        }
                        
                    }
                    else{
                        $arrReturn['status'] = 'ORDERNOTFOUND';
                    }
                }
                
                $this->response->type('json');
		$this->response->body(json_encode($arrReturn));
		return $this->response;
	}         
}
